package com.qd.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qd.common.result.ResultUtils;
import com.qd.common.utils.EmptyUtils;
import com.qd.entity.Cart;
import com.qd.entity.Users;
import com.qd.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huangshuaikang
 * @since 2024-10-18
 */
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    ICartService service;

    @GetMapping("/")
    public Object getList(Integer deskId){
        List<Cart> list = service.getList(deskId); //调用自定义方法
        return ResultUtils.returnDataSuccess(list);
    }


    @PostMapping("/")
    public Object add(@RequestBody Cart c){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("desk_id",c.getDeskId());
        queryWrapper.eq("product_id",c.getProductId());
        Cart one = service.getOne(queryWrapper);
        //判断是否为空
        if(EmptyUtils.isNotEmpty(one)){
            one.setNum(one.getNum() + c.getNum());
            if(one.getNum()==0){
                if(service.removeById(one)){
                    return ResultUtils.returnDataSuccess(c);
                }
                return ResultUtils.returnFail("删除失败");
            }else {
                if (service.updateById(one)) {
                    return ResultUtils.returnDataSuccess(c);
                }
                return ResultUtils.returnFail("修改失败");
            }
        }else {
        if(service.save(c)){
            return ResultUtils.returnDataSuccess(c);
        }
        return ResultUtils.returnFail("添加失败");
        }
    }

    @DeleteMapping("/")
    public Object del(Integer deskId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("desk_id",deskId);
        if(service.remove(queryWrapper)){
            return ResultUtils.returnSuccess();
        }
        return ResultUtils.returnFail("清空失败");
    }


}
